package com.cheng.fmmall.service.impl;

import com.cheng.fmmall.dao.UsersMapper;
import com.cheng.fmmall.entity.Users;
import com.cheng.fmmall.service.UserService;
import com.cheng.fmmall.utils.MD5Utils;
import com.cheng.fmmall.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper userMapper;

    @Override
    @Transactional
    public ResultVO userRegist(String username, String password) {
        // 1.判断当前用户是否已经存在
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        Users user = userMapper.selectOneByExample(example);

        // 2.如果不存在，插入数据
        if (user == null) {
            user = new Users();
            user.setUsername(username);
            String md5Password = MD5Utils.md5(password);
            user.setPassword(md5Password);
            user.setUserImg("img/default.png");
            user.setUserRegtime(new Date());
            user.setUserModtime(new Date());
            int i = userMapper.insertUseGeneratedKeys(user);
            if (i == 1) {
                return new ResultVO(10000, "注册成功！", user);
            } else {
                return new ResultVO(10002, "注册失败！", null);
            }
        } else {
            return new ResultVO(10001, "用户已经存在", null);
        }
    }

    @Override
    public ResultVO checkLogin(String username, String password) {
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        Users user = userMapper.selectOneByExample(example);
        // user当前不存在
        if (user == null) {
            return new ResultVO(10001, "用户不存在！", null);
        } else {
            String md5Pwd = MD5Utils.md5(password);
            if (md5Pwd.equals(user.getPassword())) {
                return new ResultVO(10000, "登陆成功！", user);
            } else {
                return new ResultVO(10001, "密码错误！", null);
            }
        }
    }
}
